package com.server.net.message;

import com.server.util.LogUtil;

/**
 * 协议分发线程
 * 所有角色都必须在内
 * 处理分配到此的角色信息
 */
public class MsgDispatcher extends Thread {

    private volatile boolean start = false;

    private volatile boolean interrupt = false;//线程是否被中断

    private MsgProcessor msgProcess = new MsgProcessor();//仅处理本dispatcher的协议

    private static long TICK_PER = 1L;

    public MsgDispatcher() {
    }

    public void startUp() {
        this.start = true;
        this.start();
    }

    public void close() {
        this.start = false;
        try {
            while (true) {
                Thread.sleep(TICK_PER);
                if (interrupt) {
                    this.interrupt();
                    break;
                }
            }
        } catch (InterruptedException e) {
            LogUtil.game.error("Exception", e);
        }
    }

    @Override
    public void run() {
        while (this.start && !interrupt) {
            try {
                Thread.sleep(TICK_PER);
                if (this.start == false) {
                    this.interrupt = true;
                }
            } catch (InterruptedException e) {
                LogUtil.game.error("Exception", e);
                break;
            }
            msgProcess.process();
        }
    }

    public void addMessagePack(MsgPack msgPack) {
        if (!this.start) {
            return;
        }
        msgProcess.addMessagePack(msgPack);
    }
}
